package com.digitalchina.lxnsy.activity.old;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.NonNull;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.bigkoo.pickerview.OptionsPickerView;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.api.BusinessConsult;
import com.digitalchina.lxnsy.api.BusinessFile;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.entity.ActivityTypeVO;
import com.digitalchina.lxnsy.entity.FileVO;
import com.digitalchina.lxnsy.entity.ShareFarmListVO;
import com.digitalchina.lxnsy.loader.GlideImageLoader;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.FrescoUtil;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.facebook.drawee.view.SimpleDraweeView;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：郑皓
 * 创建时间：2018/10/12 16:51
 * 修改备注：
 * ================================================
 */
public class AddConsultActivity extends BaseActivity {


    @Bind(R.id.tv_type)
    TextView tvType;
    @Bind(R.id.layout_type)
    RelativeLayout layoutType;
    @Bind(R.id.et_content)
    EditText etContent;
    @Bind(R.id.btn_submit)
    Button btnSubmit;
    @Bind(R.id.sdv_img0)
    SimpleDraweeView sdvImg0;
    @Bind(R.id.sdv_img1)
    SimpleDraweeView sdvImg1;
    @Bind(R.id.sdv_img2)
    SimpleDraweeView sdvImg2;
    @Bind(R.id.sdv_img3)
    SimpleDraweeView sdvImg3;

    private ShareFarmListVO vo;
    private OptionsPickerView pvOptions; // 种类选择器
    private List<ActivityTypeVO> voList = new ArrayList<>();

    private String code = "";


    public static final int REQUEST_CODE_SELECT = 100;
    private int select = 0; // -1为上传主图  其他上传详情图
    private String[] imgs = {"", "", "", ""};
    private SimpleDraweeView[] sdvArray = new SimpleDraweeView[4];

    @Override
    public void setLayout() {
        setContentLayout(R.layout.activity_add_consult);
        setTitle("发起咨询");
    }

    @Override
    public void initMember() {

        selectImage();


        sdvArray[0] = sdvImg0;
        sdvArray[1] = sdvImg1;
        sdvArray[2] = sdvImg2;
        sdvArray[3] = sdvImg3;

        // 咨询分类
        BusinessConsult.consultType(this, mHandler);

        vo = (ShareFarmListVO) getIntent().getSerializableExtra("ShareFarmListVO");

        // 条件选择器初始化
        pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {

                if (voList != null && voList.size() > 0) {
                    tvType.setText(voList.get(options1).getLabel());
                    code = voList.get(options1).getValue();
                }

            }
        })
                .setSubmitText("确定")
                .setCancelText("取消")
                .setTitleText("咨询种类")
                .setSubCalSize(16)//确定取消按钮大小
                .setLineSpacingMultiplier(1.7f) //设置两横线之间的间隔倍数（范围：1.2 - 2.0倍 文字高度）
                .setDividerColor(getResources().getColor(R.color.app_color))//设置分割线的颜色
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(18)//设置滚轮文字大小
                .setSelectOptions(0, 0)  //设置默认选中项
                .build();

    }

    private void selectImage() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);  //显示拍照按钮
        imagePicker.setMultiMode(false);    //是否多选模式
        imagePicker.setCrop(false);        //允许裁剪（单选才有效）
    }

    @Override
    public void addListener() {
        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (StringUtil.isStrEmpty(code)) {
                    showToast("请选择咨询类型");
                    return;
                }
                if (StringUtil.isStrEmpty(etContent.getText().toString())) {
                    showToast("请输入咨询内容");
                    return;
                }
                StringBuilder pictures = new StringBuilder();
                for (String img : imgs) {
                    if (!StringUtil.isStrEmpty(img))
                        pictures.append(img).append(",");
                }
                BusinessConsult.saveConsult(AddConsultActivity.this, vo.getId(), "1", code, etContent.getText().toString(), vo.getUserAccId(), pictures.toString(), mHandler);
            }
        });

        layoutType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (voList != null && voList.size() > 0)
                    pvOptions.show();
                else
                    showSnackbar("正在获取咨询分类");
            }
        });
    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case MSG.MSG_SAVE_CONSULT_SUCCESS: // 发布成功
                        showToast("发布成功，等待卖家回复。");
                        setResult(RESULT_OK);
                        finish();
                        break;
                    case MSG.MSG_SAVE_CONSULT_FIELD:
                        showToast(msg.obj.toString() + "");
                        break;
                    case MSG.MSG_CONSULT_TYPE_SUCCESS: // 咨询分类
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_CONSULT_TYPE_FIELD:
                        showToast(msg.obj.toString() + "");
                        break;
                    case MSG.MSG_FILE_UPLOAD_SUCCESS:  // 上传图片
                        dismissDialog();
                        FileVO fileVO = FastJsonUtil.getBean(msg.obj.toString(), "body", "fileStorage", FileVO.class);
                        if (fileVO == null)
                            return;

                        imgs[select] = fileVO.getName();
                        FrescoUtil.showImageSmall(imgs[select], sdvArray[select]);
                        break;
                    case MSG.MSG_FILE_UPLOAD_FIELD:
                        dismissDialog();
                        showToast(msg.obj.toString());
                        break;
                }
            }
        };
    }

    @Override
    public void callBack(Object object) {

        voList = FastJsonUtil.getListBean(object.toString(), "consultationTypeList", ActivityTypeVO.class);

        if (voList != null)
            pvOptions.setPicker(voList);

    }

    @Override
    public void rightOnClick() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.sdv_img0, R.id.sdv_img1, R.id.sdv_img2, R.id.sdv_img3})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.sdv_img0:
                selectImage(0);
                break;
            case R.id.sdv_img1:
                selectImage(1);
                break;
            case R.id.sdv_img2:
                selectImage(2);
                break;
            case R.id.sdv_img3:
                selectImage(3);
                break;
        }
    }

    // 选择图片
    private void selectImage(int i) {
        select = i;
        if (StringUtil.isStrEmpty(imgs[select])) {
            Intent intent = new Intent(this, ImageGridActivity.class);
            startActivityForResult(intent, REQUEST_CODE_SELECT);
        } else {
            new MaterialDialog.Builder(this)
                    .title("提示")
                    .content("是否删除这张照片？")
                    .positiveText("删除")
                    .negativeText("取消")
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            imgs[select] = "";
                            Uri uri = Uri.parse("res://com.digitalchina.bigdata/" + R.drawable.selector_image_add);
                            sdvArray[select].setImageURI(uri);
                        }
                    })
                    .show();
        }

    }

    /**
     * 跳转回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null && images.size() > 0) {
                    showDialog("正在上传图片...");
                    BusinessFile.imageCompressAndUpload(this, images.get(0).path, mHandler);
                }
            }
        }

    }

}
